#include "StdAfx.h"
#include "MyTimer.h"

namespace CC3501_Main_GUI {

	MyTimer::MyTimer(void)
	{
		this->timerInterval = MyTimer::sleepTime;

		// create ourself a timer
		// with a timer interval of MyTimer::sleepTime
		this->internalTimer = gcnew System::Timers::Timer( this->timerInterval );

		// register our own tick handler (i.e. do some work when the timer fires)
		// this is done using delegates.. (C++/CLI feature)
		this->addTickHandler(gcnew ElapsedEventHandler(this, &MyTimer::handleTick));
		
		// Clear initial state
		this->reset();
	}

	// Set all counts to 0
	void MyTimer::reset(void) {
		tics = 0;
	}

	// Enable the timer
	void MyTimer::resume(void) {
		this->internalTimer->Enabled = true;
	}

	// Disable the timer
	void MyTimer::pause(void) {
		this->internalTimer->Enabled = false;
	}

	// Disable the timer, and clear the ticks state
	void MyTimer::stop(void) {
		this->pause();
		this->reset();
	}

	// Allow other people to add tick handlers
	// C++/CLI feature using delegates...
	// Essentially, builds a list of functions to call when the timer fires
	void MyTimer::addTickHandler(ElapsedEventHandler^ eventHandler) {
		this->internalTimer->Elapsed += eventHandler;
	}

	// We handle our own tick using this function..
	// increment our numbers
	void MyTimer::handleTick(Object^ source, ElapsedEventArgs^ e) {
		tics += 1;
	}

	// Allow people to remove tick handlers
	void MyTimer::removeTickHandler(ElapsedEventHandler^ eventHandler){
		this->internalTimer->Elapsed -= eventHandler;
	}

	// Convert our timer tick counts to a human readable time string
	String^ MyTimer::getTimeString(void) {
		unsigned int total_seconds = tics / ( 1000 / this->timerInterval );
		unsigned int total_mins    = total_seconds / 60;
		unsigned int total_hours   = total_mins / 60;

		unsigned int seconds = total_seconds % 60;
		unsigned int minutes = total_mins % 60;

		String^ secondsString = Convert::ToString(seconds)->PadLeft(2, '0');
		String^ minutesString = Convert::ToString(minutes)->PadLeft(2, '0');
		String^ hoursString   = Convert::ToString(total_hours)->PadLeft(2, '0');
		
		String^ out = String::Concat(hoursString,":",minutesString,":",secondsString);			
		return out;
	}

}